<template>
    <div>
        <headers />
        <div class="container mb-30">
            <main-nav />
            <el-card>
                <h3>填写并核对订单信息</h3>
                <el-divider></el-divider>
                <div class="flex align-items space-between">
                    <h4>收货人信息</h4>
                    <el-link type="danger" :underline="false" @click="addEditFun('add', {})">
                        <strong>新增收货地址</strong>
                    </el-link>
                </div>

                <div class="text-center pt-30 pb-10" v-if="addrList.length === 0">
                    <el-button @click="addEditFun('add', {})">新增收货地址</el-button>
                </div>
                <div class="mt-15">
                    <addr-item v-for="(item, index) in addrList" :key="index" :item="item" @refresh="getAddressListData"
                        :selected="form.address_id === item.id" @addEditFun="addEditFun" @handleSelect="handleSelect" />
                </div>
                <div class="mt-20" v-if="!showAll && addrList.length < maxAddressesToShow">
                    <el-link :underline="false" @click="showMore">显示更多地址<i class="el-icon-arrow-down"></i></el-link>
                </div>

                <el-divider></el-divider>
                <h4>支付方式</h4>
                <div class="pt-30 pb-10">
                    <el-button :type="payType === 2 ? 'danger' : 'default'"
                        @click="payType = 2">微信支付</el-button>
                    <el-button :type="payType === 1 ? 'danger' : 'default'"
                        @click="payType = 1">支付宝支付</el-button>
                </div>
                <el-divider></el-divider>
                <!-- <strong class="text-red">测试加入购物车</strong>
                <ul>
                    <li v-for="item in prods" :key="item.id" @click="addCart(item)">ID{{ item.id }} - 商品名称：{{ item.name
                        }}</li>
                </ul>
                <el-divider></el-divider> -->

                <h4>购物车</h4>
                <div class="mt-30">
                    <cartItem v-for="item in carts" :key="item.id" :item="item" />
                </div>

                <div  class="mb-20">
                    <el-input type="textarea" placeholder="请输入备注内容" v-model="form.remark" maxlength="50" show-word-limit>
                    </el-input>
                </div>

                <el-card>
                    <div class="flex align-items space-between text-gray">
                        <p class="mb-sm">共 <span class="text-red">{{ totalNum }}</span> 件商品，合计：<span
                                class="text-red">￥{{ totalPrice }}</span></p>
                        <el-button type="danger" size="large" @click="createOrder">立即支付</el-button>
                        <!-- <el-button type="danger" size="large" @click="payment">立即支付(有订单号)</el-button> -->
                    </div>
                </el-card>
            </el-card>
        </div>
        <footers />
        <addrDialog ref="addrDialogRef" @refresh="getAddressListData" />
    </div>
</template>

<script>
import { mapState, mapMutations } from "vuex"
import headers from "@/components/header.vue"
import footers from "@/components/footer.vue"
import mainNav from "@/components/mainNav.vue"
import addrItem from "./components/addrItem.vue"
import addrDialog from '../products/components/addrDialog.vue'
import cartItem from "./components/cartItem.vue"
import { getAddressList, buyOne, pay } from "@/api/apis"

export default {
    name: "Procucts",
    components: {
        headers,
        footers,
        mainNav,
        addrItem,
        addrDialog,
        cartItem
    },
    data () {
        return {
            payStatus: 0, // 支付状态 0未支付 1已支付 2支付失败
            payType: 1,
            order_sn: '', // 订单号
            addrList: [],
            maxAddressesToShow: 5, // 默认显示的地址数量
            showAll: false, // 是否显示全部地址            
            form: {
                address_id: '', // 地址 ID
                goods_id: '', // 商品 ID
                sku_id: '', // 商品 SKU ID
                remark: '', // 备注
                source_type: 1, // 1pc2手机
                number: 1, // 购买数量
            }
        }
    },
    computed: {
        ...mapState('carts', ['carts']),
        totalPrice () {
            return this.$store.getters['carts/getTotalPrice']
        },
        totalNum () {
            return this.$store.getters['carts/getTotalNum']
        },

        // 计算当前应该显示的地址列表
        visibleAddresses () {
            // 如果显示全部地址，则返回所有地址
            if (this.showAll) {
                return this.addrList
            }
            // 否则返回最多 maxAddressesToShow 条地址
            return this.addrList.slice(0, this.maxAddressesToShow)
        },
    },
    created () {

    },
    mounted () {
        this.getAddressListData();
        const order_sn = localStorage.getItem('order_sn');
        if (order_sn) {
            this.order_sn = order_sn;
        }
    },
    methods: {
        ...mapMutations('carts', ['addCart', 'clearCart']), // 数组写法 添加商品至购物车
        getAddressListData(){
            getAddressList().then(res => {
                if (res.code === 1) {
                    this.addrList = res.data;
                    // 选择is_default=1的地址
                    let defaultAddr = this.addrList.find(item => item.is_default === 1);
                    this.form.address_id = defaultAddr ? defaultAddr.id : '';
                }
            })
        },
        showMore () {
            // 当点击显示更多时，设置 showAll 为 true 以显示所有地址
            this.showAll = true
        },        
        addEditFun (type, item) {
            this.$refs.addrDialogRef.showDialog(type, item)
        },
        // 选择地址
        handleSelect(data){
            this.form.address_id = data.id;
        },
        /* addCart (item) {
            // 调用 store 中的 addCart 方法，将商品添加到购物车
            this.$store.commit('addCart', item)
        }, */
        createOrder(){
            this.form.goods_id = this.carts[0].id;
            this.form.sku_id = 1;
            this.form.number = this.carts[0].number;
            this.form.source_type = 1; // 1pc2手机
            buyOne(this.form).then(res => {
                if (res.code === 1) {
                    this.$message.success('订单创建成功！');
                    this.order_sn = res.order_sn;
                    localStorage.setItem('order_sn', res.order_sn);
                    // 跳转到支付页面
                    this.payment();
                } else {
                    this.$message.error(res.msg);
                }
            })
        },
        payment(){
            pay({
                pay_type: this.payType,
                order_sn: this.order_sn
            }).then(res => {
                if (res.code === 1) {
                    this.$message.success(res.msg);
                    this.clearCart();
                    // 跳转到我的订单页面
                    this.$router.push({ name: 'orders' });
                } else {
                    this.$message.error(res.msg);
                }
            })
        }
    }
}
</script>

<style lang="less" scoped></style>